package cn.zgf.core;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author GaoFeng2017
 * @date 2018-02-21 09:44:38
 **/

public class BeanListHandler<T> implements ContentHandler<List<T>> {
    private Class<T> beanClass;

    public BeanListHandler(Class<T> beanClass) {
        this.beanClass = beanClass;
    }

    @Override
    public List<T> handle(List<String[]> content, String[] heads) {
        Field[] fields = beanClass.getDeclaredFields();
        List<String> headList = Arrays.asList(heads);
        List<T> beanList = new ArrayList<>(content.size());
        try {
            for (String[] items : content) {
                T bean = beanClass.newInstance();
                for (Field field : fields) {
                    /*field.isAnnotationPresent()*/
                    Column column = field.getAnnotation(Column.class);
                    if (column == null) {
                        continue;
                    }
                    int index = headList.indexOf(column.value());
                    field.setAccessible(true);
                    field.set(bean,items[index]);
                }
                beanList.add(bean);
            }
            return beanList;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
